package pl.com.like.sequoia.dao.bio;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import pl.com.like.sequoia.dao.GenericDao;
import pl.com.like.sequoia.model.bio.BioObjectAlign;
import pl.com.like.sequoia.model.bio.BioObjectHandler;

@Transactional
public class BioObjectAlignDao extends GenericDao<BioObjectAlign, Long> implements IBioObjectAlignDao {

	public BioObjectAlignDao() {
		super(BioObjectAlign.class);
	}

	@SuppressWarnings("unchecked")
	public Boolean comparisonExists(String parentObjId, String compareToObjId) {
		Boolean exists = Boolean.FALSE;
		Criteria crit = getCriteria();
		crit.createAlias("bioObjectA", "parent");
		crit.createAlias("bioObjectB", "child");
		crit.add(Restrictions.or(Restrictions.and(Restrictions.like("parent.name", parentObjId), Restrictions.like(
				"child.name", compareToObjId)), Restrictions.and(Restrictions.like("parent.name", compareToObjId),
				Restrictions.like("child.name", parentObjId))));
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		List<BioObjectAlign> compList = crit.list();
		if (compList == null || compList.isEmpty()) {
			exists = Boolean.FALSE;
		} else {
			exists = Boolean.TRUE;
		}
		return exists;
	}

	public BioObjectAlign get(String objectId) {
		Criteria crit = getCriteria();
		crit.add(Restrictions.like("name", objectId));
		return (BioObjectAlign) crit.uniqueResult();
	}

	public List<BioObjectHandler> getComparisonPair(String idComparison) {
		Criteria crit = getCriteria();
		crit.add(Restrictions.like("name", idComparison));
		BioObjectAlign align = (BioObjectAlign) crit.uniqueResult();
		ArrayList<BioObjectHandler> resultList = new ArrayList<BioObjectHandler>();
		resultList.add(align.getBioObjectA());
		resultList.add(align.getBioObjectB());
		return resultList;
	}

	@SuppressWarnings("unchecked")
	public List<BioObjectAlign> getSearchList(String objectId) {
		Criteria crit = getCriteria();
		crit.createAlias("bioObjectA", "parent");
		crit.createAlias("bioObjectB", "child");
		crit.add(Restrictions.or(Restrictions.like("name", objectId), Restrictions.or(Restrictions.like("parent.name",
				objectId), Restrictions.like("child.name", objectId))));
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return crit.list();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void save(BioObjectAlign o) {
		super.save(o);
	}

}
